package com.securitydemo.demo.controller;

/**
 * @author hyf
 * @Title: ${file_name}
 * @Package com.securitydemo.demo.controller
 * @Description: ${todo}
 * @date 2018/5/10下午11:22
 */

import com.securitydemo.demo.po.User;
import com.securitydemo.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Joe Grandja
 */
@Controller
public class MainController {

    @Autowired
    private IUserService userService;



    @RequestMapping("/")
    public String root() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/user/index")
    public String userIndex() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username;
        if (principal instanceof UserDetails) {
             username = ((UserDetails)principal).getUsername();
            UserDetails userDetails= ((UserDetails)principal);
            userDetails.getAuthorities();
        } else {
             username = principal.toString();
        }
        System.out.println("username:"+username);
        System.out.println(principal.toString());
        System.out.println(SecurityContextHolder.getContext().getClass().getName());
        return "user/index";
    }

    @RequestMapping("/login")
    public String login() {
        System.out.println("login");
        return "login";
    }

    @RequestMapping("/login2")
    public String login2() {
        System.out.println("login2");
        return "login2";
    }


    @RequestMapping(value = "/login3")
    public String login3() {
        System.out.println("login3");
        return "login3";
    }

    //logoutSuccess
    @RequestMapping("/logoutSuccess")
    public String logoutSuccess()
    {
        System.out.println("logoutSuccess");
        return "logoutSuccess";
    }

    @RequestMapping("/login-error")
    public String loginError(Model model) {
        System.out.println("loginError");
        model.addAttribute("loginError", true);
        return "login";
    }


    @RequestMapping("/get_user")
    @ResponseBody
    public User getUser(Model model) {
        System.out.println("get User");
        //        model.addAttribute("loginError", true);
       User user= userService.getOne();
        return user;
    }


}